// src/components/ToolKit\DBCompare.tsx
import React, { useState, useEffect } from "react";
import { 
  Card, 
  Row, 
  Col, 
  Input, 
  Button, 
  Checkbox, 
  Table, 
  Tabs, 
  Tag, 
  Progress,
  Space,
  Select,
  Form,
  Divider,
  Alert,
  Popover,
  Radio,
  Dropdown
} from "antd";
import { 
  DatabaseOutlined, 
  PlayCircleOutlined, 
  DownloadOutlined,
  CheckSquareOutlined,
  BorderOutlined,
  ThunderboltOutlined,
  PlusOutlined,
  CloseOutlined
} from "@ant-design/icons";
import { useStore } from '../../stores';
import { observer } from "mobx-react-lite";
import { useNavigate } from 'react-router-dom';
import * as styles from '../../assets/styles/toolkit/dbCompare.module';
import { format } from 'sql-formatter';

const { TabPane } = Tabs;
const { Option } = Select;
const { TextArea } = Input;

interface TableItem {
  key: string;
  name: string;
  description: string;
  selected: boolean;
}

interface ComparisonResult {
  tableName: string;
  status: 'success' | 'warning' | 'error';
  totalRows: number;
  matchedRows: number;
  mismatchedRows: number;
  missingRows: number;
  extraRows: number;
}

// 定义对比场景类型
type ComparisonScenario = 'same-db' | 'different-db';

// 定义标签类型
interface TagItem {
  id: number;
  name: string;
}

const DatabaseCompare: React.FC = observer(() => {
  const store = useStore();
  const navigate = useNavigate();
  
  // 添加格式化控制状态
  const [isFormattingEnabled, setIsFormattingEnabled] = useState(true);
  // 添加新标签输入状态
  const [newTag, setNewTag] = useState("");
  
  // 获取数据库连接状态
  const isCoreConnected = store.toolkit.dbConnections.core.isConnected;
  const isRefactoredConnected = store.toolkit.dbConnections.refactored.isConnected;
  const isDbConnected = isCoreConnected || isRefactoredConnected;
  
  // // 获取所有已连接的数据库卡片
  // const connectedDbs = store.toolkit.dbCards.filter(card => card.isConnected);
   // 获取所有已连接的数据库卡片（从两个地方获取：dbCards和connectedDbCards）
   const connectedDbs = [
    ...store.toolkit.dbCards.filter(card => card.isConnected),
    ...store.toolkit.connectedDbCards
  ];
  
  // 获取数据库配置信息
  const coreDbConfig = store.toolkit.dbConnections.core.config;
  const refactoredDbConfig = store.toolkit.dbConnections.refactored.config;
  
  // 使用 store 中的状态替代本地状态
  const tables = store.toolkit.tables;
  const results = store.toolkit.results;
  const comparisonScenario = store.toolkit.comparisonScenario;
  const sameDbSql = store.toolkit.sameDbSql;
  const differentDbSql1 = store.toolkit.differentDbSql1;
  const differentDbSql2 = store.toolkit.differentDbSql2;
  const tags = store.toolkit.tags;
  const isShared = store.toolkit.isShared;

  // 格式化SQL语句的函数
  const formatSql = (sql: string) => {
    // 如果格式化未启用，直接返回原始SQL
    if (!isFormattingEnabled) {
      return sql;
    }
    
    try {
      return format(sql, {
        language: 'sql',
        keywordCase: 'upper',
        linesBetweenQueries: 2,
      });
    } catch (error) {
      // 如果格式化失败，返回原始SQL
      return sql;
    }
  };


  // 使用 store 中的方法替代本地状态更新函数
  const toggleTableSelection = (key: string) => {
    store.toolkit.setTableSelected(key, !store.toolkit.tables.find(t => t.key === key)?.selected);
  };

  const selectAllTables = () => {
    store.toolkit.selectAllTables();
  };

  const deselectAllTables = () => {
    store.toolkit.deselectAllTables();
  };

  const selectedCount = tables.filter(table => table.selected).length;

  // 表单更新方法
  const handleSameDbSqlChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
    const formattedSql = formatSql(e.target.value);
    store.toolkit.setSameDbSql(formattedSql);
  };

  const handleDifferentDbSql1Change = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
    const formattedSql = formatSql(e.target.value);
    store.toolkit.setDifferentDbSql1(formattedSql);
  };

  const handleDifferentDbSql2Change = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
    const formattedSql = formatSql(e.target.value);
    store.toolkit.setDifferentDbSql2(formattedSql);
  };

  const setComparisonScenario = (scenario: "same-db" | "different-db") => {
    store.toolkit.setComparisonScenario(scenario);
  };

  // 标签相关处理函数
  const handleAddTag = () => {
    if (newTag.trim() !== "") {
      store.toolkit.addTag(newTag.trim());
      setNewTag("");
    }
  };

  const handleRemoveTag = (id: number) => {
    store.toolkit.removeTag(id);
  };

  // 分享选项处理函数
  const handleShareChange = (e: any) => {
    store.toolkit.setIsShared(e.target.value === "yes");
  };

  const getStatusTag = (status: 'success' | 'warning' | 'error') => {
    switch (status) {
      case 'success':
        return <Tag color="success">一致</Tag>;
      case 'warning':
        return <Tag color="warning">警告</Tag>;
      case 'error':
        return <Tag color="error">错误</Tag>;
      default:
        return <Tag>未知</Tag>;
    }
  };

  const columns = [
    {
      title: '表名',
      dataIndex: 'tableName',
      key: 'tableName',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: 'success' | 'warning' | 'error') => getStatusTag(status),
    },
    {
      title: '总行数',
      dataIndex: 'totalRows',
      key: 'totalRows',
    },
    {
      title: '一致行数',
      dataIndex: 'matchedRows',
      key: 'matchedRows',
    },
    {
      title: '不一致行数',
      dataIndex: 'mismatchedRows',
      key: 'mismatchedRows',
    },
    {
      title: '缺失行数',
      dataIndex: 'missingRows',
      key: 'missingRows',
    },
    {
      title: '多余行数',
      dataIndex: 'extraRows',
      key: 'extraRows',
    },
  ];

  // 动态渲染已连接的数据库
  const renderConnectedDbs = () => {
    if (connectedDbs.length === 0) {
      return (
        <Col span={24}>
          <div style={{ textAlign: 'center', padding: '20px' }}>
            <span>暂无已连接的数据库，请先在环境配置页面连接数据库。</span>
            {/* <Button 
              type="link" 
              onClick={() => navigate('/toolkit/environment')}
            >
              前往环境配置
            </Button> */}
          </div>
        </Col>
      );
    }

    return (
      <>
        {connectedDbs.map(db => (
          <Col span={12} key={db.id}>
            <Popover 
              content={
                <div>
                  <p><strong>主机地址:</strong> {db.config.host}</p>
                  <p><strong>端口:</strong> {db.config.port}</p>
                  <p><strong>数据库名:</strong> {db.config.database}</p>
                  <p><strong>用户名:</strong> {db.config.username}</p>
                </div>
              } 
              title="数据库信息"
            >
              <div 
                className={styles.tableItem(false)}
                style={{ cursor: 'pointer', display: 'flex', alignItems: 'center' }}
              >
                <Checkbox 
                  checked={!!store.toolkit.selectedDbCards[db.id.toString()]}
                  onChange={(e) => {
                    // 根据不同场景处理选择逻辑
                    if (comparisonScenario === 'same-db') {
                      // 同一数据库场景：确保只能选择一个数据库
                      const newSelectedDbCards: Record<string, boolean> = {};
                      // 只有在当前是未选中状态时才选中它（确保只选中一个）
                      if (!store.toolkit.selectedDbCards[db.id.toString()]) {
                        newSelectedDbCards[db.id.toString()] = true;
                      }
                      store.toolkit.setSelectedDbCards(newSelectedDbCards);
                    } else {
                      // 不同数据库场景：可以多选
                      store.toolkit.setDbCardSelected(db.id, e.target.checked);
                    }
                  }}
                  style={{ marginRight: '10px' }}
                />
                <div>
                  <div className={styles.tableItemName}>
                    {db.name}
                  </div>
                  <div className={styles.tableItemDescription}>
                    {db.config.database}
                  </div>
                </div>
              </div>
            </Popover>
          </Col>
        ))}
      </>
    );
  };

  // 检查是否有选中的数据库卡片
  const getSelectedDbCardsCount = () => {
    return connectedDbs.filter(db => store.toolkit.selectedDbCards[db.id.toString()]).length;
  };

  // 检查选中的数据库卡片是否都有输入SQL语句
  const areAllSelectedDbCardsHaveSql = () => {
    const selectedDbCards = connectedDbs.filter(db => store.toolkit.selectedDbCards[db.id.toString()]);
    
    // 检查每个选中的数据库是否都有输入SQL
    for (const db of selectedDbCards) {
      // 这里简化处理，实际项目中应该为每个数据库维护独立的SQL输入状态
      if (db.id === 1 && !differentDbSql1.trim()) {
        return false;
      }
      if (db.id !== 1 && !differentDbSql2.trim()) {
        return false;
      }
    }
    
    return true;
  };

  // 检查开始对比按钮是否应该启用
  const isStartButtonEnabled = () => {
    if (!isDbConnected) return false;
    
    if (comparisonScenario === 'same-db') {
      // 同一数据库场景：需要选中一个数据库且SQL不为空
      return getSelectedDbCardsCount() === 1 && sameDbSql.trim() !== '';
    } else {
      // 不同数据库场景：需要至少选中两个数据库，且所有选中的数据库都有输入SQL
      return getSelectedDbCardsCount() >= 2 && areAllSelectedDbCardsHaveSql();
    }
  };

  return (
    <div>
      <div className={styles.header}>
        <div className={styles.headerContainer}>
          <div className={styles.headerContent}>
            <DatabaseOutlined className={styles.icon} />
            <span>数据库对比工具</span>
          </div>
        </div>
      </div>

      <Row gutter={[24, 24]}>
        {/* 数据库连接状态提醒 */}
        <Col span={24}>
          <Alert
            message="数据库连接状态"
            description={
              <div>
                {!isDbConnected? (
                  <span>
                    请先在环境配置页面连接数据库。
                    <Button 
                      type="link" 
                      onClick={() => navigate('/toolkit/environment')}
                    >
                      前往环境配置
                    </Button>
                  </span>
                ) : (
                  <div>
                    <div>✓ 数据库环境已就绪</div>
                  </div>
                )}
              </div>
            }
            type={!isDbConnected ? "warning" : "success"}
            showIcon
          />
        </Col>
            

        {/* 选择数据库 */}
        <Col span={24} >
                <Card 
                title={
                  <span>
                    <DatabaseOutlined style={{ marginRight: 8,marginTop:-50 }} />
                    选择数据库
                  </span>
                }
                extra={
                  comparisonScenario === 'same-db' ? (
                    <Space>
                      <Button icon={<CheckSquareOutlined />} onClick={() => {
                        // 同一数据库场景只能选中一个，所以只选中第一个
                        if (connectedDbs.length > 0) {
                          const newSelectedDbCards: Record<string, boolean> = {};
                          newSelectedDbCards[connectedDbs[0].id.toString()] = true;
                          store.toolkit.setSelectedDbCards(newSelectedDbCards);
                        }
                      }}>
                        全选
                      </Button>
                      <Button icon={<BorderOutlined />} onClick={() => {
                        store.toolkit.setSelectedDbCards({});
                      }}>
                        取消全选
                      </Button>
                    </Space>
                  ) : null
                }
              >
                {/* <Alert
                  message="提示"
                  description="以下数据库连接信息来自环境配置页面，确保在环境配置页面已成功连接数据库。"
                  type="info"
                  style={{ marginBottom: 20 }}
                /> */}
                

                  <div>
                    <h3>已连接的数据库</h3>
                    <Row gutter={24}>
                      {renderConnectedDbs()}
                    </Row>
                  </div>
   
              </Card>
         

         
        </Col>

        {/* 对比场景选择 */}
        <Col span={24}>
          <Card title={
            <span>
              <ThunderboltOutlined style={{ marginRight: 8 }} />
              对比场景选择
            </span>
          }>
            <div style={{ marginBottom: 20 }}>
              <Select 
                value={comparisonScenario} 
                onChange={val => setComparisonScenario(val as ComparisonScenario)}
                style={{ width: '100%' }}
              >
                <Option value="same-db">同一数据库中多条SQL语句对比</Option>
                <Option value="different-db">不同数据库中SQL语句对比</Option>
              </Select>
            </div>
            

          </Card>
        </Col>
        <Col span={24}>
          <Card title={
            <span>
              <ThunderboltOutlined style={{ marginRight: 8 }} />
              对比场景执行
            </span>
          }>
            {/* 同一数据库对比表单 */}
            {comparisonScenario === 'same-db' && (
              <div>
                <h3>同一数据库中多条SQL语句对比</h3>
                <p>示例：</p>
                <pre style={{ background: '#f5f5f5', padding: 10, borderRadius: 4 }}>
                  {`select * from user where userid in (11111,22222);
select * from order where userid in (11111,22222);`}
                </pre>
                <Form layout="vertical">
                  
                  <div className={styles.formItem}>
                    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                      <label className={styles.formLabel}>SQL语句（每行一条SQL语句）</label>
                      <Checkbox 
                        checked={isFormattingEnabled} 
                        onChange={(e) => setIsFormattingEnabled(e.target.checked)}
                      >
                        自动格式化SQL
                      </Checkbox>
                    </div>
                    <TextArea
                      value={sameDbSql}
                      onChange={handleSameDbSqlChange}
                      rows={6}
                      placeholder="请输入SQL语句，每行一条"
                      allowClear
                    />
                  </div>
                </Form>
              </div>
            )}
            
            {/* 不同数据库对比表单 */}
            {comparisonScenario === 'different-db' && (
              <div>
                <h3>不同数据库中SQL语句对比</h3>
                <p>示例：</p>
                <pre style={{ background: '#f5f5f5', padding: 10, borderRadius: 4 }}>
                  {`数据库1: select * from global.user where userid=11111;
数据库2: select * from au.user where userid=222222;`}
                </pre>
                
                {/* 当选中了数据库时，显示相应的SQL输入表单 */}
                {getSelectedDbCardsCount() > 0 && (
                  <Form layout="vertical">
                    {connectedDbs.map(db => {
                      if (store.toolkit.selectedDbCards[db.id.toString()]) {
                        return (
                          <React.Fragment key={db.id}>
                            <Divider>{db.name} SQL语句</Divider>
                            <div className={styles.formItem}>
                              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                                <span></span>
                                <Checkbox 
                                  checked={isFormattingEnabled} 
                                  onChange={(e) => setIsFormattingEnabled(e.target.checked)}
                                >
                                  自动格式化SQL
                                </Checkbox>
                              </div>
                              <TextArea
                                value={db.id === 1 ? differentDbSql1 : differentDbSql2} // 简化处理，实际应有独立状态
                                onChange={(e) => {
                                  if (db.id === 1) {
                                    handleDifferentDbSql1Change(e);
                                  } else {
                                    handleDifferentDbSql2Change(e);
                                  }
                                }}
                                rows={4}
                                placeholder={`请输入${db.name}的SQL语句`}
                                allowClear
                              />
                            </div>
                          </React.Fragment>
                        );
                      }
                      return null;
                    })}
                  </Form>
                )}
              </div>
            )}
            

                  {/* 第一行：标签输入区域 */}
                  <div style={{ display: 'flex', alignItems: 'center', flexWrap: 'wrap', gap: 8, marginBottom: 16 }}>
                    {tags.map(tag => (
                      <div key={tag.id} style={{ display: 'flex', alignItems: 'center', backgroundColor: '#f5f5f5', padding: '4px 8px', borderRadius: 4 }}>
                        <span>{tag.name}</span>
                        <Button 
                          type="text" 
                          icon={<CloseOutlined />} 
                          onClick={() => handleRemoveTag(tag.id)}
                          size="small"
                          style={{ marginLeft: 4 }}
                        />
                      </div>
                    ))}
                    <Input 
                      value={newTag}
                      onChange={(e) => setNewTag(e.target.value)}
                      onPressEnter={handleAddTag}
                      style={{ width: 120 }}
                      placeholder="输入标签"
                    />
                    <Button icon={<PlusOutlined />} onClick={handleAddTag}>
                      添加标签
                    </Button>
                  </div>
                  
                  {/* 第二行：分享选项 */}
                  <div style={{ marginBottom: 16 }}>
                    <span style={{ marginRight: 16 }}>分享:</span>
                    <Radio.Group value={isShared ? "yes" : "no"} onChange={handleShareChange}>
                      <Radio value="no">是</Radio>
                      <Radio value="yes">否</Radio>
                    </Radio.Group>
                  </div>



            <div style={{ marginTop: 20 }}>
              <Button 
                type="primary" 
                icon={<PlayCircleOutlined />}
                disabled={!isStartButtonEnabled()}
              >
                开始对比
              </Button>
            </div>
            </Card>
        </Col>
        {/* 表选择卡片 */}
        {/* <Col span={24}>
          <Card 
            title={
              <span>
                <DatabaseOutlined style={{ marginRight: 8 }} />
                选择对比表
              </span>
            }
            extra={
              <Space>
                <Button icon={<CheckSquareOutlined />} onClick={selectAllTables}>
                  全选
                </Button>
                <Button icon={<BorderOutlined />} onClick={deselectAllTables}>
                  取消全选
                </Button>
              </Space>
            }
          >
            <Row gutter={24}>
              <Col span={12}>
                <h3>用户相关表</h3>
                <div className={styles.tableContainer}>
                  {tables.slice(0, 5).map(table => (
                    <div 
                      key={table.key}
                      onClick={() => toggleTableSelection(table.key)}
                      className={styles.tableItem(table.selected)}
                    >
                      <div className={styles.tableItemName}>{table.name}</div>
                      <div className={styles.tableItemDescription}>{table.description}</div>
                    </div>
                  ))}
                </div>
              </Col>
              <Col span={12}>
                <h3>业务相关表</h3>
                <div className={styles.tableContainer}>
                  {tables.slice(5).map(table => (
                    <div 
                      key={table.key}
                      onClick={() => toggleTableSelection(table.key)}
                      className={styles.tableItem(table.selected)}
                    >
                      <div className={styles.tableItemName}>{table.name}</div>
                      <div className={styles.tableItemDescription}>{table.description}</div>
                    </div>
                  ))}
                </div>
              </Col>
            </Row>
            <div className={styles.footer}>
              <div>
                已选择 <strong>{selectedCount}</strong> 个表进行对比
              </div>
              <Button 
                type="primary" 
                icon={<PlayCircleOutlined />}
                disabled={!isDbConnected}
              >
                开始对比
              </Button>
            </div>
          </Card>
        </Col> */}

        {/* 对比结果卡片 */}
        <Col span={24}>
          <Card 
            title={
              <span>
                <DatabaseOutlined style={{ marginRight: 8 }} />
                对比结果
              </span>
            }
            extra={
              <Button icon={<DownloadOutlined />}>
                导出报告
              </Button>
            }
          >
            <Tabs defaultActiveKey="1">
              <TabPane tab="概览" key="1">
                <Row gutter={24}>
                  <Col span={6}>
                    <div className={styles.progressContainer}>
                      <div className={styles.progressLabel}>对比状态</div>
                      <div className={styles.progressValue}>已完成</div>
                    </div>
                    <div className={styles.progressContainer}>
                      <div className={styles.progressLabel}>对比表数量</div>
                      <div className={styles.progressValue}>3 / 3</div>
                      <Progress percent={100} showInfo={false} strokeColor="#52c41a" />
                    </div>
                    <div className={styles.progressContainer}>
                      <div className={styles.progressLabel}>一致数据</div>
                      <div className={styles.progressValue}>12,458 行</div>
                      <Progress percent={92} showInfo={false} strokeColor="#52c41a" />
                    </div>
                  </Col>
                  <Col span={18}>
                    <h3>表对比详情</h3>
                    <Table 
                      dataSource={results} 
                      columns={columns} 
                      pagination={{ pageSize: 5 }} 
                      rowKey="tableName"
                    />
                  </Col>
                </Row>
              </TabPane>
              <TabPane tab="详细结果" key="2">
                <div>详细结果内容</div>
              </TabPane>
              <TabPane tab="差异详情" key="3">
                <div>差异详情内容</div>
              </TabPane>
            </Tabs>
          </Card>
        </Col>
      </Row>
    </div>
  );
});

export default DatabaseCompare;